package com.codebase.alicloud.dingding;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.open.app.api.OpenDingTalkStreamClientBuilder;
import com.dingtalk.open.app.api.security.AuthClientCredential;
import com.taobao.api.ApiException;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class DingTalkUtil {
    private static final String URL = "https://oapi.dingtalk.com/robot/send?access_token=c2bb1482a0fb6b159da70335d135a56a5e8c09755864d0db728813edd558afbd";


    private static final String Client_ID = "dingwm0igw92eey8ezss";
    private static final String Client_Secret = "vrNOHd0-fmu_Pm7QECh9OCfqVAs1Nn8OZnP4cFGonqvan3kKPiPi_TWUqzsO_hYn";


    public static void main(String[] args) throws Exception {
        receiveMsg();
    }

    private static void receiveMsg() throws Exception {
        OpenDingTalkStreamClientBuilder
                .custom()
                .credential(new AuthClientCredential(Client_ID, Client_Secret))
                //注册机器人监听器
                .registerCallbackListener("/v1.0/im/bot/messages/get", robotMessage -> {
                    //开发者根据自身业务需求，处理机器人回调
                    try {
                        processMsg(robotMessage);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    return robotMessage;
                })
                .build().start();
    }

    /**
     * 处理消息
     *
     * @param robotMessage {"senderPlatform":"Win","conversationId":"ciddr9nzQECcOP11VFHVvFtmw==","atUsers":[{"dingtalkId":"$:LWCP_v1:$OGNhPGC4lozC37fNHe3mj9MC/WBvnSbb"}],
     *                     "chatbotCorpId":"dingdc69c02a436cf19cffe93478753d9884","chatbotUserId":"$:LWCP_v1:$OGNhPGC4lozC37fNHe3mj9MC/WBvnSbb","msgId":"msgZ412BBC6KAjkP6fKtblogA==",
     *                     "senderNick":"侯凯","isAdmin":true,"senderStaffId":"27580331653344","sessionWebhookExpiredTime":1751513518961,
     *                     "createAt":1751508118744,"senderCorpId":"dingdc69c02a436cf19cffe93478753d9884","conversationType":"2",
     *                     "senderId":"$:LWCP_v1:$yZw8b48GqAcVxg5dqdTlug==","conversationTitle":"测试消息","isInAtList":true,
     *                     "sessionWebhook":"https://oapi.dingtalk.com/robot/sendBySession?session=5f39b6a0e2f055a774e2469583a0d858",
     *                     "text":{"content":"  qq"},
     *                     "robotCode":"dingwm0igw92eey8ezss","msgtype":"text"}
     * @throws Exception
     */
    private static void processMsg(Object robotMessage) throws Exception {
        String msg = robotMessage.toString();
        System.out.println(msg);
        JSONObject jsonObject = JSON.parseObject(msg);
        msg = jsonObject.getByPath("$.text.content").toString().trim();
        System.out.println(msg);

        if (msg.startsWith("help")) {
            processHelp();
            return;
        }

        if (msg.startsWith("report")) {
            processReport();
            return;
        }
        if (msg.startsWith("data")) {
            processData(msg);
            return;
        }

        processHelp();
    }


    private static final String dataItem_1 = "总发生额,总客户数,承兑发生额,背书发生额,贴现发生额,质押发生额,保证发生额";
    private static final String dataItem_2 = "总发生额,总客户数,承兑发生笔数,背书发生额,背书发生笔数";
    private static final String split = ":";
    private static final String YYYYMMDD = "YYYYMMDD";
    private static final String key1 = "data-业务数据总览-总规模";
    private static final String key2 = "data-昨日数据";
    private static final String key3 = "data-平台-沂链通";
    private static final String key4 = "data-平台-商票板";
    private static final String key5 = "data-平台-承信账户";
    private static final String key6 = "data-平台-滨链通";
    private static final String key7 = "data-平台-其他";
    private static final String key8 = "data-部门-业务一部";
    private static final String key9 = "data-部门-业务三部";
    private static final String key10 = "data-部门-账户业务部";
    private static final String key11 = "data-承信账户总览-总规模";
    private static final String key12 = "data-承信账户总览-新增规模";

    private static void processHelp() throws ApiException {
        String msg = "help   获取机器人操作命令\n" +
                "report   重新生成报告图片" +
                "data   数据修复,data命令格式\n" +
                "\t  " + key1 + split + YYYYMMDD + split + dataItem_1 + "\n" +
                "\t  " + key2 + split + YYYYMMDD + split + dataItem_1 + "\n" +
                "\t  " + key3 + split + YYYYMMDD + split + dataItem_1 + "\n" +
                "\t  " + key4 + split + YYYYMMDD + split + dataItem_1 + "\n" +
                "\t  " + key5 + split + YYYYMMDD + split + dataItem_1 + "\n" +
                "\t  " + key6 + split + YYYYMMDD + split + dataItem_1 + "\n" +
                "\t  " + key7 + split + YYYYMMDD + split + dataItem_1 + "\n" +
                "\t  " + key8 + split + YYYYMMDD + split + dataItem_1 + "\n" +
                "\t  " + key9 + split + YYYYMMDD + split + dataItem_1 + "\n" +
                "\t  " + key10 + split + YYYYMMDD + split + dataItem_1 + "\n" +
                "\t  " + key11 + split + YYYYMMDD + split + dataItem_2 + "\n" +
                "\t  " + key12 + split + YYYYMMDD + split + dataItem_2;
        sendTextMsg(msg);
    }

    private static void processData(String msg) throws Exception {
        String[] msgArray = msg.split(split);
        if (msgArray.length != 3) {
            sendTextMsg("命令格式错误");
            return;
        }
        String msgHead = msgArray[0];
        if (msgHead == null || msgHead.trim().isEmpty()) {
            sendTextMsg("关键字错误");
            return;
        }
        String msgDay = msgArray[1];
        String msgValues = msgArray[2];
        if (!isValidDate(msgDay)) {
            sendTextMsg("日期格式错误 正确格式YYYYMMDD 如20240703");
            return;
        }
        String[] values = msgValues.split(",");
        switch (msgHead) {
            case key1:
                billDingNotice("overall_scope", msgDay, values);
                break;
            case key2:
                billDingNotice("yesterdays_scope", msgDay, values);
                break;
            case key3:
                billDingNotice("yiliantong_scope", msgDay, values);
                break;
            case key4:
                billDingNotice("spb_scope", msgDay, values);
                break;
            case key5:
                billDingNotice("cx_account_scope", msgDay, values);
                break;
            case key6:
                billDingNotice("binliantong_scope", msgDay, values);
                break;
            case key7:
                billDingNotice("others", msgDay, values);
                break;
            case key8:
                billDingNotice("first_department", msgDay, values);
                break;
            case key9:
                billDingNotice("third_department", msgDay, values);
                break;
            case key10:
                billDingNotice("account_department", msgDay, values);
                break;
            case key11:
                billDingNotice("account_overall_scope", msgDay, values);
                break;
            case key12:
                billDingNotice("account_yesterdays_scope", msgDay, values);
                break;
            default:
                sendTextMsg("关键字错误");
        }
    }

    private static void billDingNotice(String dbkey, String day, String[] values) throws Exception {
        sendTextMsg("数据更新完成");
    }

    private static void processReport() throws Exception {
        sendMarkdownMsg("![YY](https://spb-dev.oss-cn-beijing.aliyuncs.com/shendu-dev/2022-07-28/%E4%BE%9B%E7%A5%A8%E4%B8%9A%E7%BB%A9%E6%8A%A5%E8%A1%A8%E6%B5%8B%E8%AF%95.png)");
    }


    private static void sendTextMsg(String msg) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient(URL);
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype("text");
        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
        text.setContent(msg);
        request.setText(text);
        client.execute(request);
    }

    private static void sendMarkdownMsg(String text) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient(URL);
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype("markdown");
        OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
        markdown.setTitle("消息标题");
        markdown.setText(text);
        request.setMarkdown(markdown);
        client.execute(request);
    }


    // 正则表达式：匹配YYYYMMDD格式
    private static final String DATE_REGEX = "^(\\d{4})(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])$";

    // 校验日期格式和有效性
    public static boolean isValidDate(String dateStr) {
        // 首先检查格式是否匹配
        if (!dateStr.matches(DATE_REGEX)) {
            return false;
        }

        try {
            // 使用DateTimeFormatter严格解析日期，确保日期有效
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            LocalDate date = LocalDate.parse(dateStr, formatter);

            // 额外验证：检查月份和日期是否匹配（例如2月30日会被拒绝）
            int year = Integer.parseInt(dateStr.substring(0, 4));
            int month = Integer.parseInt(dateStr.substring(4, 6));
            int day = Integer.parseInt(dateStr.substring(6, 8));

            // 检查月份天数（考虑闰年）
            if (day > date.lengthOfMonth()) {
                return false;
            }

            return true;
        } catch (DateTimeParseException e) {
            return false;
        }
    }
}
